package com.mf.morefun.ui.myclass.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.mf.morefun.R;
import com.mf.morefun.adapter.ArrangeHomeWorkAdapter;
import com.mf.morefun.base.BaseBusFragment;
import com.mf.morefun.bean.ArrangeItemBean;
import com.mf.morefun.bean.ClassListBean;
import com.mf.morefun.bean.DoHomeWorkBean;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.listener.HomeWorkListListener;
import com.mf.morefun.requestbean.RequestArrangeBean;
import com.mf.morefun.requestbean.RequestArrangeHomeWorkBean;
import com.mf.morefun.requestbean.RequestEditClassHomeWorkBean;
import com.mf.morefun.requestbean.RequestUserBean;
import com.mf.morefun.ui.myclass.CreateClassHomeWorkActivity;
import com.mf.morefun.ui.myclass.HomeWorkCountActivity;
import com.mf.morefun.widget.BackIdeaPop;
import com.mf.morefun.widget.NetErrorPop;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhcx.zhcxlibrary.utils.DateUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.addapp.pickers.common.LineConfig;
import cn.addapp.pickers.picker.DatePicker;

public class ArrangeHomeWorkFragment extends BaseBusFragment {
    @BindView(R.id.iv_add)
    ImageView ivAdd;
    @BindView(R.id.lv_arrange)
    ListView lvArrange;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.edit_homework)
    EditText editHomework;
    @BindView(R.id.tv_classname)
    TextView tvClassname;
    @BindView(R.id.tv_startdate)
    TextView tvStartdate;
    @BindView(R.id.tv_enddate)
    TextView tvEnddate;
    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    @BindView(R.id.rl_bg)
    RelativeLayout rlBg;
    private ClassListBean mClassListBean;
    private ClassicsHeader mClassicsHeader = null;
    private int pageNo = 1;
    private int totlePage = 1;
    private List<ArrangeItemBean> mArrangeItemList = new ArrayList<>();
    private ArrangeHomeWorkAdapter adapter;
    private int selectYear = 0;
    private int selectMonth = 0;
    private int selectDay = 0;
    private int mYear = 2019;
    private int mMonth = 5;
    private int mDay = 9;
    private int selectEnableYear = 0;
    private int selectEnableMonth = 0;
    private int selectEnableDay = 0;
    private int currentPosition = 0;

    public static ArrangeHomeWorkFragment newInstance(ClassListBean mClassListBean) {
        ArrangeHomeWorkFragment newFragment = new ArrangeHomeWorkFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("CLASSBEAN", mClassListBean);
        newFragment.setArguments(bundle);
        return newFragment;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_arrangehomework;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        Bundle args = getArguments();
        if (null != args) {
            mClassListBean = (ClassListBean) args.getSerializable("CLASSBEAN");
        } else {
            mClassListBean = new ClassListBean();
        }
        if (null != mClassListBean) {
            initGetArrangeList(mClassListBean.getClassBelong().getId(), true);
        }
        rlBg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        mClassicsHeader = (ClassicsHeader) refreshLayout.getRefreshHeader();
        int delda = new Random().nextInt(7 * 24 * 60 * 60 * 1000);
        mClassicsHeader.setLastUpdateTime(new Date(System.currentTimeMillis() - delda));
        mClassicsHeader.setTimeFormat(new SimpleDateFormat("更新于 MM-dd HH:mm", Locale.CHINA));
        refreshLayout.getLayout().bringChildToFront(lvArrange);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNo = 1;
                if (null != mClassListBean) {
                    initGetArrangeList(mClassListBean.getClassBelong().getId(), true);
                }
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageNo++;
                if (pageNo < totlePage) {
                    if (null != mClassListBean) {
                        initGetArrangeList(mClassListBean.getClassBelong().getId(), false);
                    }
                } else {
                    if (null != refreshLayout) {
                        refreshLayout.finishLoadMore();
                        refreshLayout.finishRefresh();
                        refreshLayout.setEnableLoadMore(false);
                    }
                }
            }
        });
        adapter = new ArrangeHomeWorkAdapter(getActivity(), mArrangeItemList);
        lvArrange.setAdapter(adapter);
        rlBg.setVisibility(View.GONE);
        rlBg.getBackground().setAlpha(100);
        adapter.setListListener(new HomeWorkListListener() {
            @Override
            public void callBack(int position, int type) {
                if (mArrangeItemList.size() > 0) {
                    if (type == 0) {//布置
                        if (isAble(mArrangeItemList, position)){
                            currentPosition = position;
                            rlBg.setVisibility(View.VISIBLE);
                            initTime(mArrangeItemList, position);
                        }else {
                            ToastUtils.show(getActivity(), "该作业已经超过有限期", 100);
                        }
                    } else {//操作
                        try {
                            showPop(mArrangeItemList, position, isAble(mArrangeItemList, position));
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                    }
                }
            }
        });
        lvArrange.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (null != mArrangeItemList && mArrangeItemList.size() > 0) {
                    if (!StringUtils.isEmpty(mArrangeItemList.get(position).getStartdate()) && !StringUtils.isEmpty(mArrangeItemList.get(position).getEnddate())){
                        Intent mIntent = new Intent(getActivity(), HomeWorkCountActivity.class);
                        mIntent.putExtra("CLASSID", mArrangeItemList.get(position).getClassId());
                        mIntent.putExtra("HOMEWORKID", mArrangeItemList.get(position).getId());
                        mIntent.putExtra("HOMEWORKNAME", mArrangeItemList.get(position).getName());
                        startActivity(mIntent);
                    }
                }
            }
        });
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction("DELETECLASSHOMEWORK");
        getActivity().registerReceiver(mReceiver, mFilter);
    }

    private boolean isAble(List<ArrangeItemBean> mArrangeItemList, int position){
        try {
            if (StringUtils.isEmpty(mArrangeItemList.get(position).getEnddate())){
                return true;
            }else {
                long end = DateUtils.DEFAULT_DATE_FORMAT.parse(mArrangeItemList.get(position).getEnddate() + " 23:59:59").getTime();
                if (end < System.currentTimeMillis()){
                    return false;
                }else {
                    return true;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    private void initTime(List<ArrangeItemBean> mArrangeItemList, int position) {
        mYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date(System.currentTimeMillis())));
        mMonth = Integer.parseInt(new SimpleDateFormat("MM").format(new Date(System.currentTimeMillis())));
        mDay = Integer.parseInt(new SimpleDateFormat("dd").format(new Date(System.currentTimeMillis())));
        if (mArrangeItemList.size() > 0) {
            String enableEnd = mArrangeItemList.get(position).getEnddate();
            if (StringUtils.isEmpty(enableEnd)) {
                selectEnableYear = mYear;
                selectEnableMonth = mMonth;
                selectEnableDay = mDay;
            } else {
                String enable[] = enableEnd.split("-");
                try {
                    if (enable.length == 3) {
                        selectEnableYear = Integer.parseInt(enable[0]);
                        selectEnableMonth = Integer.parseInt(enable[1]);
                        selectEnableDay = Integer.parseInt(enable[2]);
                    } else {
                        selectEnableYear = mYear;
                        selectEnableMonth = mMonth;
                        selectEnableDay = mDay;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    selectEnableYear = mYear;
                    selectEnableMonth = mMonth;
                    selectEnableDay = mDay;
                }
            }
            String enableStart = mArrangeItemList.get(position).getStartdate();
            if (StringUtils.isEmpty(enableStart)) {
                selectYear = mYear;
                selectMonth = mMonth;
                selectDay = mDay;
            } else {
                String enable[] = enableStart.split("-");
                try {
                    if (enable.length == 3) {
                        selectYear = Integer.parseInt(enable[0]);
                        selectMonth = Integer.parseInt(enable[1]);
                        selectDay = Integer.parseInt(enable[2]);
                    } else {
                        selectYear = mYear;
                        selectMonth = mMonth;
                        selectDay = mDay;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    selectYear = mYear;
                    selectMonth = mMonth;
                    selectDay = mDay;
                }
            }
        } else {
            selectEnableYear = mYear;
            selectEnableMonth = mMonth;
            selectEnableDay = mDay;
            selectYear = mYear;
            selectMonth = mMonth;
            selectDay = mDay;
        }
        String year = "";
        String month = "";
        String day = "";
        if (selectYear < 10) {
            year = "0" + selectYear;
        } else {
            year = "" + selectYear;
        }
        if (selectMonth < 10) {
            month = "0" + selectMonth;
        } else {
            month = "" + selectMonth;
        }
        if (selectDay < 10) {
            day = "0" + selectDay;
        } else {
            day = "" + selectDay;
        }
        tvStartdate.setText(year + "-" + month + "-" + day);
        if (selectEnableYear < 10) {
            year = "0" + selectEnableYear;
        } else {
            year = "" + selectEnableYear;
        }
        if (selectEnableMonth < 10) {
            month = "0" + selectEnableMonth;
        } else {
            month = "" + selectEnableMonth;
        }
        if (selectEnableDay < 10) {
            day = "0" + selectEnableDay;
        } else {
            day = "" + selectEnableDay;
        }
        tvEnddate.setText(year + "-" + month + "-" + day);
        if (null != mClassListBean) {
            tvClassname.setText(mClassListBean.getClassBelong().getName());
        }
        editHomework.setText(mArrangeItemList.get(position).getName());
        if (!StringUtils.isEmpty(editHomework.getText().toString())) {
            editHomework.setFocusable(false);
        }
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("DELETECLASSHOMEWORK")) {
                if (mArrangeItemList.size() > 0) {
                    initDeleteHomework(intent.getIntExtra("POSITION", 0));
                }
            }
        }
    };

    private void initDeleteHomework(int position) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.DELETEHOMEWORK);
        RequestUserBean requestUserBean = new RequestUserBean();
        requestUserBean.setId(mArrangeItemList.get(position).getId());
        params.setBodyContent(JSON.toJSONString(requestUserBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    ResultBean mResult = JSON.parseObject(result, ResultBean.class);
                    if (mResult.getErrorCode() == 0) {
                        mArrangeItemList.remove(position);
                        mHandler.sendEmptyMessage(100);
                    } else {
                        ToastUtils.show(getActivity(), mResult.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private PopupWindow mDoPop;

    //弹出操作的弹框   需要三个按钮   设置有效期， 重置密码， 删除用户
    private void showPop(List<ArrangeItemBean> mArrangeItemList, int position, boolean isAble) {
        if (null == mDoPop) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_create, null);
            RelativeLayout rl_bg = view.findViewById(R.id.rl_bg);
            rl_bg.getBackground().setAlpha(100);
            TextView tv_record = view.findViewById(R.id.tv_record);//修改名称
            tv_record.setText("改名");
            tv_record.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mDoPop.dismiss();
                    mDoPop = null;
                    showChangeName(1, mArrangeItemList, position);
                }
            });
            TextView tv_video = view.findViewById(R.id.tv_video);
            tv_video.setText("编辑");
            tv_video.setOnClickListener(new View.OnClickListener() {//修改图片
                @Override
                public void onClick(View v) {
                    mDoPop.dismiss();
                    mDoPop = null;
                    Intent mIntent = new Intent(getActivity(), CreateClassHomeWorkActivity.class);
                    mIntent.putExtra("name", mArrangeItemList.get(position).getName());
                    mIntent.putExtra("CLASSID", mArrangeItemList.get(position).getClassId());
                    mIntent.putExtra("HOMEWORKID", mArrangeItemList.get(position).getId());
                    startActivity(mIntent);
                }
            });
            TextView tv_creation = view.findViewById(R.id.tv_creation);
            tv_creation.setText("删除");
            tv_creation.setOnClickListener(new View.OnClickListener() {//删除班级
                @Override
                public void onClick(View v) {
                    mDoPop.dismiss();
                    mDoPop = null;
                    BackIdeaPop pops = new BackIdeaPop(getActivity());
                    pops.showPop("确定要删除 " + mArrangeItemList.get(position).getName() + "吗?", 10, position);
                }
            });
            TextView tvCancel = view.findViewById(R.id.tv_cancel);
            tvCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mDoPop.dismiss();
                    mDoPop = null;
                }
            });
            View v_record = view.findViewById(R.id.v_record);
            View v_video = view.findViewById(R.id.v_video);
            if (!isAble){
                tv_record.setVisibility(View.GONE);
                tv_video.setVisibility(View.GONE);
                v_record.setVisibility(View.GONE);
                v_video.setVisibility(View.GONE);
            }else {
                tv_record.setVisibility(View.VISIBLE);
                tv_video.setVisibility(View.VISIBLE);
                v_record.setVisibility(View.VISIBLE);
                v_video.setVisibility(View.VISIBLE);
            }
            mDoPop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
            mDoPop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            mDoPop.setBackgroundDrawable(new BitmapDrawable());
            mDoPop.setFocusable(true);
            mDoPop.update();
            mDoPop.showAtLocation(view, Gravity.CENTER, 0, 0);
            mDoPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    mDoPop.dismiss();
                    mDoPop = null;
                }
            });
        }
    }

    private void initEditSubmit(String name, String classId, List<ArrangeItemBean> mArrangeItemList, int position) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.EDITARRANGE);
        RequestEditClassHomeWorkBean requestCreateClassHomeWorkBean = new RequestEditClassHomeWorkBean();
        requestCreateClassHomeWorkBean.setId(mArrangeItemList.get(position).getId());
        requestCreateClassHomeWorkBean.setClassId(classId);
        requestCreateClassHomeWorkBean.setName(name);
        params.setBodyContent(JSON.toJSONString(requestCreateClassHomeWorkBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    ResultBean mResult = JSON.parseObject(result, ResultBean.class);
                    if (mResult.getErrorCode() == 0) {
                        mArrangeItemList.get(position).setName(name);
                        mHandler.sendEmptyMessage(100);
                    } else {
                        ToastUtils.show(getActivity(), mResult.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    //接受RecordMusicService发过来的消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMusicMessage(String message) {
        if (!StringUtils.isEmpty(message)) {
            if (message.equals("yes")) {
                if (null != mClassListBean) {
                    pageNo = 1;
                    initGetArrangeList(mClassListBean.getClassBelong().getId(), true);
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        try {
            getActivity().unregisterReceiver(mReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initGetArrangeList(String classId, boolean isRefresh) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.ARRANGELIST);
        RequestArrangeBean requestArrangeBean = new RequestArrangeBean();
        requestArrangeBean.setOrderBy("a.startdate desc");
        requestArrangeBean.setPageSize(20);
        requestArrangeBean.setPageNo(pageNo);
        RequestArrangeBean.MfTpDetailBean mfTpDetailBean = new RequestArrangeBean.MfTpDetailBean();
        mfTpDetailBean.setClassId(classId);
        requestArrangeBean.setMfTpDetail(mfTpDetailBean);
        params.setBodyContent(JSON.toJSONString(requestArrangeBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (null != refreshLayout) {
                    refreshLayout.finishLoadMore();
                    refreshLayout.finishRefresh();
                }
                if (isRefresh) {
                    mArrangeItemList.clear();
                }
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        if (!StringUtils.isEmpty(resultBean.getResult())) {
                            DoHomeWorkBean doHomeWorkBean = JSON.parseObject(resultBean.getResult(), DoHomeWorkBean.class);
                            totlePage = doHomeWorkBean.getTotalPage();
                            if (!StringUtils.isEmpty(doHomeWorkBean.getList())) {
                                List<ArrangeItemBean> arrangeItemBeanList = JSON.parseArray(doHomeWorkBean.getList(), ArrangeItemBean.class);
                                mArrangeItemList.addAll(arrangeItemBeanList);
                            }
                        }
                    }
                }
                mHandler.sendEmptyMessage(100);
            }


            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (null != refreshLayout) {
                    refreshLayout.finishLoadMore();
                    refreshLayout.finishRefresh();
                }
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(getActivity());
                    errorPop.showPop("");
                    break;
                case 100:
                    if (null != adapter) {
                        adapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    };

    @Override
    protected void initData() {

    }

    @OnClick({R.id.iv_add, R.id.tv_startdate, R.id.tv_enddate, R.id.tv_cancel, R.id.tv_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_add:
                showChangeName(0, null, 0);
                break;
            case R.id.tv_startdate:
                DatePicker pickers = new DatePicker(getActivity(), DatePicker.YEAR_MONTH_DAY);
                pickers.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
                pickers.setRangeStart(1900, 1, 1);
                pickers.setRangeEnd(2040, 12, 31);
                pickers.setSelectedItem(selectYear, selectMonth, selectDay);
                pickers.setLineVisible(true);
                pickers.setCanLoop(false);
                pickers.setWeightEnable(true);
                pickers.setLineColor(0xfff0f0f0);
                pickers.setTopPadding(10);
                pickers.setSubmitTextColor(Color.parseColor("#00CC99"));
                pickers.setSelectedTextColor(Color.parseColor("#333333"));
                LineConfig lineConfig = new LineConfig();
                lineConfig.setColor(Color.parseColor("#eaeaea"));
                pickers.setLineConfig(lineConfig);
                pickers.setCanLinkage(true);
                pickers.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                    @Override
                    public void onDatePicked(String year, String month, String day) {
                        String time = year + "-" + month + "-" + day;
                        if (StringUtils.isEmpty(tvEnddate.getText().toString())){
                            tvStartdate.setText(time);
                        }else {
                            try {
                                long startTime = DateUtils.DATE_YEAR_MONTH_DAY.parse(time).getTime();
                                long endTime = DateUtils.DATE_YEAR_MONTH_DAY.parse(tvEnddate.getText().toString()).getTime();
                                if (endTime < startTime){
                                    ToastUtils.show(getActivity(), "截止时间不能小于开始时间", 100);
                                }else {
                                    tvStartdate.setText(time);
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                                ToastUtils.show(getActivity(), "截止时间不能小于开始时间", 100);
                            }
                        }
                    }
                });
                pickers.show();
                break;
            case R.id.tv_enddate:
                DatePicker picker = new DatePicker(getActivity(), DatePicker.YEAR_MONTH_DAY);
                picker.setFillScreen(false);
                picker.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
                picker.setRangeStart(mYear, mMonth, mDay);
                picker.setRangeEnd(2040, 12, 31);
                picker.setSelectedItem(selectEnableYear, selectEnableMonth, selectEnableDay);
                picker.setLineVisible(true);
                picker.setCanLoop(false);
                picker.setTopPadding(10);
                picker.setSubmitTextColor(Color.parseColor("#00CC99"));
                picker.setSelectedTextColor(Color.parseColor("#333333"));
                LineConfig lineConfigs = new LineConfig();
                lineConfigs.setColor(Color.parseColor("#eaeaea"));
                picker.setLineConfig(lineConfigs);
                picker.setCanLinkage(true);
                picker.setWeightEnable(true);
                picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                    @Override
                    public void onDatePicked(String year, String month, String day) {
                        String time = year + "-" + month + "-" + day;
                        if (StringUtils.isEmpty(tvStartdate.getText().toString())){
                            tvEnddate.setText(time);
                        }else {
                            try {
                                long startTime = DateUtils.DATE_YEAR_MONTH_DAY.parse(tvStartdate.getText().toString()).getTime();
                                long endTime = DateUtils.DATE_YEAR_MONTH_DAY.parse(time).getTime();
                                if (endTime < startTime){
                                    ToastUtils.show(getActivity(), "截止时间不能小于开始时间", 100);
                                }else {
                                    tvEnddate.setText(time);
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                                ToastUtils.show(getActivity(), "截止时间不能小于开始时间", 100);
                            }
                        }
                    }
                });
                picker.show();
                break;
            case R.id.tv_cancel:
                rlBg.setVisibility(View.GONE);
                break;
            case R.id.tv_sure:
                rlBg.setVisibility(View.GONE);
                if (mArrangeItemList.size() > 0 && null != mClassListBean) {
                    initArrangeHomeWork();
                }
                break;
        }
    }

    private void initArrangeHomeWork() {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.ARRANGEHOMEWORK);
        RequestArrangeHomeWorkBean requestArrangeHomeWorkBean = new RequestArrangeHomeWorkBean();
        requestArrangeHomeWorkBean.setId(mArrangeItemList.get(currentPosition).getId());
        requestArrangeHomeWorkBean.setClassId(mClassListBean.getClassBelong().getId());
        requestArrangeHomeWorkBean.setStartdate(tvStartdate.getText().toString());
        requestArrangeHomeWorkBean.setEnddate(tvEnddate.getText().toString());
        params.setBodyContent(JSON.toJSONString(requestArrangeHomeWorkBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        mArrangeItemList.get(currentPosition).setStartdate(tvStartdate.getText().toString());
                        mArrangeItemList.get(currentPosition).setEnddate(tvEnddate.getText().toString());
                        mHandler.sendEmptyMessage(100);
                        ToastUtils.show(getActivity(), resultBean.getMessage(), 100);
                    } else {
                        ToastUtils.show(getActivity(), resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private PopupWindow mNamePop = null;

    //改名字
    private void showChangeName(int type, List<ArrangeItemBean> mArrangeItemList, int position) {
        try {
            if (null == mNamePop) {
                LayoutInflater inflater = getLayoutInflater();
                View view = inflater.inflate(R.layout.layout_popclass, null);
                // 这里启动头像
                RelativeLayout rl_bg = view.findViewById(R.id.rl_bg);
                rl_bg.getBackground().setAlpha(100);
                EditText edit_name = view.findViewById(R.id.edit_name);
                edit_name.setHint("请填写一个作业的名称");
                ImageView iv_cancel = view.findViewById(R.id.iv_cancel);
                iv_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mNamePop.dismiss();
                        mNamePop = null;
                    }
                });
                ImageView iv_sure = view.findViewById(R.id.iv_sure);
                iv_sure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (StringUtils.isEmpty(edit_name.getText().toString())) {
                            ToastUtils.show(getActivity(), "请填写一个作业的名称", 100);
                            return;
                        }
                        mNamePop.dismiss();
                        mNamePop = null;
                        if (null != mClassListBean) {
                            if (type == 0) {
                                //把名字跟班级ID带过去
                                Intent mIntent = new Intent(getActivity(), CreateClassHomeWorkActivity.class);
                                mIntent.putExtra("name", edit_name.getText().toString());
                                mIntent.putExtra("CLASSID", mClassListBean.getClassBelong().getId());
                                startActivity(mIntent);
                            } else {
                                initEditSubmit(edit_name.getText().toString(), mClassListBean.getClassBelong().getId(), mArrangeItemList, position);
                            }
                        }
                    }
                });
                mNamePop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
                mNamePop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                mNamePop.setBackgroundDrawable(new BitmapDrawable());
                mNamePop.setFocusable(true);
                mNamePop.update();
                mNamePop.showAtLocation(view, Gravity.CENTER, 0, 0);
                mNamePop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        mNamePop.dismiss();
                        mNamePop = null;
                    }
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
